#include "importlicensefilewidget.h"
#include "ui_importlicensefilewidget.h"
#include <QMessageBox>
#include <QGSettings>
#include <QDebug>

extern "C" {
#include <kylin-activation.h>
}


ImportLicenseFileWidget::ImportLicenseFileWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ImportLicenseFileWidget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);
    this->setProperty("useStyleWindowManager",false);
    m_dropWid=new DropWidget;
    ui->dropwidget->layout()->addWidget(m_dropWid);


    deleteLabel_1 = new MyLabel(ui->deletewidget_1);
    QHBoxLayout *deleteLayout_1 = new QHBoxLayout;
    deleteLayout_1 ->setContentsMargins(4,4,4,4);
    deleteLayout_1->addWidget(deleteLabel_1);
    ui->deletewidget_1->setLayout(deleteLayout_1);

    deleteLabel_2 = new MyLabel(ui->deletewidget_2);
    QHBoxLayout *deleteLayout_2 = new QHBoxLayout;
    deleteLayout_2 ->setContentsMargins(4,4,4,4);
    deleteLayout_2->addWidget(deleteLabel_2);
    ui->deletewidget_2->setLayout(deleteLayout_2);
//    deleteLabel_1->setPixmap(pixmap);

    connect(deleteLabel_1, &MyLabel::Clicked, this, &ImportLicenseFileWidget::deleteLabelSlot);
    connect(deleteLabel_2, &MyLabel::Clicked, this, &ImportLicenseFileWidget::deleteLabelSlot);

    connect(m_dropWid, &DropWidget::addLicenseFile, this, &ImportLicenseFileWidget::setFileLabel);


    if(QGSettings::isSchemaInstalled(QString("org.ukui.style").toLocal8Bit()))
    {
        Interface interface;
        QPixmap pixmap(QIcon::fromTheme("edit-delete-symbolic").pixmap(QSize(16,16)));
        QGSettings* gsetting=new QGSettings(QString("org.ukui.style").toLocal8Bit(),QByteArray(),this);
        if(gsetting->keys().contains("styleName"))
        {
            if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
            {
                pixmap = interface.drawSymbolicColoredPixmap(pixmap);
                deleteLabel_1->setPixmap(pixmap);
                deleteLabel_2->setPixmap(pixmap);
            }
            else
            {
//                pixmap = interface.drawSymbolicBlackColoredPixmap(pixmap);
                deleteLabel_1->setPixmap(pixmap);
                deleteLabel_2->setPixmap(pixmap);
            }
            connect(gsetting,&QGSettings::changed,[=](const QString &key){
                Interface interface1;
                QPixmap pixmap1(QIcon::fromTheme("edit-delete-symbolic").pixmap(QSize(16,16)));
                if(key=="styleName")
                {
                    if(gsetting->get("style-name").toString()=="ukui-dark" || gsetting->get("style-name").toString()=="ukui-black")
                    {
                        pixmap1 = interface1.drawSymbolicColoredPixmap(pixmap1);
                        deleteLabel_1->setPixmap(pixmap1);
                        deleteLabel_2->setPixmap(pixmap1);
                    }
                    else
                    {
//                        pixmap1 = interface1.drawSymbolicBlackColoredPixmap(pixmap1);
                        deleteLabel_1->setPixmap(pixmap1);
                        deleteLabel_2->setPixmap(pixmap1);
                    }
                }
            });
        }
    }
}

ImportLicenseFileWidget::~ImportLicenseFileWidget()
{
    delete m_dropWid;
    delete ui;
}

void ImportLicenseFileWidget::paintEvent(QPaintEvent *event)
{
    Interface interface;
    interface.setFontSize(ui->label);
}

void ImportLicenseFileWidget::on_returnbtn_clicked()
{
    ui->activebtn->setEnabled(false);
    emit returnSignal();
}

void ImportLicenseFileWidget::clearData()
{
    m_dropWid->cleanData();
    ui->filenamelabel_1->clear();
    ui->filenamelabel_2->clear();
    ui->fileiconlabel_1->clear();
    ui->fileiconlabel_2->clear();
    ui->deletewidget_1->setVisible(false);
    ui->deletewidget_2->setVisible(false);
}

void ImportLicenseFileWidget::on_activebtn_clicked()
{
    QStringList licenseFilePathList=m_dropWid->getLicenseFilePathList();
    if(!licenseFilePathList.isEmpty() && licenseFilePathList.size()==2)
    {
        QString path_1=licenseFilePathList.at(0);
        QString path_2=licenseFilePathList.at(1);
        QString l_file, i_file;
        QFileInfo info(path_1);
        if(info.fileName().contains("LICENSE", Qt::CaseInsensitive))
        {
            l_file=path_1;
            i_file=path_2;
        }
        else
        {
            l_file=path_2;
            i_file=path_1;
        }

        QMessageBox *box=nullptr;
        int ret=license_check(l_file.toLocal8Bit().data(),i_file.toLocal8Bit().data());
        if(ret!=0)
        {
            QString error=kylin_activation_get_result_message(ret);
            box=new QMessageBox(QMessageBox::Warning, NULL, QString(error+ tr("!(error code#" ) + QString::number(ret).rightJustified(4,'0')  +")"), QMessageBox::NoButton,this);
            QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
            box->setDefaultButton(closeButton);
//            box=new QMessageBox(QMessageBox::Warning, NULL, QString(error+ tr("!(error code#" ) + QString::number(ret).rightJustified(4,'0')  +")"), QMessageBox::Close,this);
            box->exec();
            delete box;
        }
        else
        {
            if(slif)
            {
                if(isSiteLicense(l_file))
                {
                    if(import_auth_file(path_1.toLocal8Bit().data()) && import_auth_file(path_2.toLocal8Bit().data()))
                    {
                        //激活成功
                        emit activateSucceed();
                        exit_service();
                    }
                }
                else
                {
                    box=new QMessageBox(QMessageBox::Information, NULL, QString(tr("Not site license file!")),QMessageBox::NoButton,this);
                    QPushButton *closeButton = box->addButton(tr("Close"), QMessageBox::AcceptRole);
                    box->setDefaultButton(closeButton);
                    box->exec();
                    delete box;
                }
            }
            else
            {
                if(import_auth_file(path_1.toLocal8Bit().data()) && import_auth_file(path_2.toLocal8Bit().data()))
                {
                    if(isSiteLicense(l_file))
                    {
                        //跳转获成功界面
                        emit activateSucceed();
                    }
                    else
                    {
                        //导入授权文件成功，跳转至主界面
                        emit returnSignal();
                    }
                    exit_service();
                }
            }
        }
    }
}

bool ImportLicenseFileWidget::isSiteLicense(QString lpath)
{
    QFile file(lpath);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<"Can't open the file!";
        return false;
    }
    while (!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        if(str.length()>6)
        {
            if(str.left(6) == "METHOD")
            {
                if(str.mid(7,5) == "place")
                {
                    return true;
                }
            }
        }
    }
    return false;
}

void ImportLicenseFileWidget::isSiteLicenseInterFace(bool sl)
{
    if(sl)
    {
        ui->remindlabel->setText(tr("Please select the authorization file you want to import, and then click the Activate button."));
        ui->label->setText(tr("Import site license file"));
        ui->activebtn->setText(tr("Activate"));
        ui->returnbtn->setVisible(true);
        slif = true;
    }
    else{
        ui->remindlabel->setText(tr("Please select the authorization file you want to import, and then click the import button."));
        ui->label->setText(tr("Import license file"));
        ui->activebtn->setText(tr("import"));

        slif = false;
        QString lpath = "/etc/LICENSE";
        QString ipath = "/etc/.kyinfo";
        int ret = license_check(lpath.toLocal8Bit().data(), ipath.toLocal8Bit().data());
        if(ret != 0)
        {
            ui->returnbtn->setVisible(false);
        }
        else
        {
            ui->returnbtn->setVisible(true);
        }
    }
}

void ImportLicenseFileWidget::setFileLabel(QStringList licenseFileNameList)
{
    qDebug()<<"the licensefilename"<<licenseFileNameList;
    for(int index=0; index<licenseFileNameList.size(); index++)
    {
        if(index==0)
        {
            qDebug()<<"index==0";
            QIcon icon=QIcon::fromTheme("text-plain");
            ui->fileiconlabel_1->setPixmap(QPixmap(icon.pixmap(QSize(16,16))));
            ui->filenamelabel_1->setText(licenseFileNameList.at(index));
            ui->activebtn->setEnabled(true);
            ui->deletewidget_1->setVisible(true);
        }
        else
        {
            qDebug()<<"index==else";
            QIcon icon=QIcon::fromTheme("text-plain");
            ui->fileiconlabel_2->setPixmap(QPixmap(icon.pixmap(QSize(16,16))));
            ui->filenamelabel_2->setText(licenseFileNameList.at(index));
            ui->activebtn->setEnabled(true);
            ui->deletewidget_2->setVisible(true);
        }
    }
}

void ImportLicenseFileWidget::deleteLabelSlot(QLabel *label)
{
    if(label==deleteLabel_1)
    {
        //删除list中的内容
        m_dropWid->deleteFile(ui->filenamelabel_1->text());
        //2中的显示切换到1来
        if(ui->filenamelabel_2->text().isEmpty())
        {
            ui->filenamelabel_1->clear();
            ui->fileiconlabel_1->clear();
            ui->deletewidget_1->setVisible(false);

        }
        else
        {
            ui->filenamelabel_1->setText(ui->filenamelabel_2->text());

            ui->fileiconlabel_2->clear();
            ui->filenamelabel_2->clear();
            ui->deletewidget_2->setVisible(false);
        }
    }
    else
    {
        //删除list中的内容
        m_dropWid->deleteFile(ui->filenamelabel_2->text());

        ui->fileiconlabel_2->clear();
        ui->filenamelabel_2->clear();
        ui->deletewidget_2->setVisible(false);
    }
}

void ImportLicenseFileWidget::checkLicense()
{
    QString lpath = "/etc/LICENSE";
    QString ipath = "/etc/.kyinfo";
    int ret = license_check(lpath.toLocal8Bit().data(), ipath.toLocal8Bit().data());
    if(ret!=0&&ret!=82)
    {
//        QMessageBox *box=nullptr;
        QString error=kylin_activation_get_result_message(ret);
//        QMessageBox *box=new QMessageBox(QMessageBox::Warning,,QString(error+ tr("!(error code#" ) + QString::number(ret).rightJustified(4,'0')  +")"), QMessageBox::Close,this);
        QMessageBox *box=new QMessageBox();
        box->setText(QString(error+ tr("!(error code#" ) + QString::number(ret).rightJustified(4,'0')  +")"));
        box->setIcon(QMessageBox::Icon::Warning);
        box->addButton(tr("Retry"), QMessageBox::NoRole);
        box->exec();
        delete box;
    }else{
        qDebug()<<"LICENSE check failed: License file not found.";
    }
}
